package net.martinimix.edesk.search;

import com.bluemartini.dna.BMContext;
import com.bluemartini.dna.BMException;
import com.bluemartini.dna.BusinessObject;
import com.bluemartini.dna.DNAList;
import com.bluemartini.dna.DNAStringArray;
import com.bluemartini.util.BasicBusinessObjectUtil;

/**
 * Provides methods common to multiple record search implementations.
 * 
 * @author Scott Rossillo
 *
 */
public abstract class AbstractRecordSearch implements RecordSearch{

	/**
	 * Creates a new abstract record search.
	 */
	protected AbstractRecordSearch() {
		super();
	}

	/**
	 * Returns the given business object as a generic "OBJECT" business object 
	 * as expected by Enterprise Desktop search.
	 */
	protected BusinessObject getGenericObject(BusinessObject object) throws BMException {
	
		BusinessObject genericObject = BMContext.createBusinessObject("OBJECT");
		genericObject.setLongID(object.getLongID());
		genericObject.setInteger("__TYPE", object.getInteger("__TYPE"));
		
		genericObject.setVersion(BasicBusinessObjectUtil.getObjectVersion(object.getLongID()));
		genericObject.setObjectName(object.getObjectName());
		genericObject.setString("shortDesc", object.getString("shortDesc"));
		genericObject.setString("path", object.getString("path"));
	
		return genericObject;
	}

	/**
	 * Returns a properly formatted list of search results for the given 
	 * search input.  This implementation validates the given <code>searchInput</code>
	 * and then delegates to {@link #searchInternal(String, int, int, DNAStringArray)}.
	 * 
	 * @see net.martinimix.edesk.search.RecordSearch#search(com.bluemartini.dna.BusinessObject)
	 */
	public final DNAList search(final BusinessObject searchInput) throws BMException {
		
		final String searchTerms = searchInput.getString("searchFor", "");
		final int firstRow = searchInput.getInteger("firstRow", 0);
		final int maxRows = searchInput.getInteger("maxRows_cd", 0);
		final DNAStringArray objectTypes = searchInput.getStringArray("objectTypes");
		
		if(searchTerms == null || searchTerms.trim().equals("")) {
			throw new BMException("Please enter text to search for!");
		}
		
		return this.searchInternal(searchTerms, firstRow, maxRows, objectTypes);
	}
	
	/**
	 * Returns a properly formatted list of search results for the given 
	 * search terms.
	 *  
	 * @param searchTerms the terms to search for
	 * @param firstRow the first row for the current search request
	 * @param maxRows the maxiumum number of rows to return
	 * @param objectTypes an array of object types being searched for
	 * @return a <code>DNAList</code> containing the search results
	 * @throws BMException if an error occurs while conducting the search
	 */
	protected abstract DNAList searchInternal(
			final String searchTerms, 
			final int firstRow, 
			final int maxRows,
			final DNAStringArray objectTypes) throws BMException;
	
}